package com.alibaba.basic.service.impl;

import com.alibaba.basic.mapper.BaseMapper;
import com.alibaba.basic.query.BaseQuery;
import com.alibaba.basic.service.IBaseService;
import com.alibaba.basic.util.PageList;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Transactional(propagation = Propagation.SUPPORTS, readOnly = true)
public class BaseServiceImpl<T> implements IBaseService<T> {

    @Autowired
    private BaseMapper<T> baseMapper;

    @Override
    public List<T> findAll() {
        return baseMapper.findAll();
    }

    @Override
    public T findOne(Long id) {
        return baseMapper.findOne(id);
    }

    @Transactional
    @Override
    public void add(T t) {
        baseMapper.add(t);
    }

    @Transactional
    @Override
    public void delete(Long id) {
        baseMapper.delete(id);
    }

    @Transactional
    @Override
    public void update(T t) {
        baseMapper.update(t);
    }

    @Override
    public PageList<T> queryPage(BaseQuery baseQuery) {
        // 先查询总数
        Long totals = baseMapper.queryCount(baseQuery);
        if (totals < 1) {
            return new PageList<>();
        }
        // 再查询分页数据
        List<T> data = baseMapper.queryPage(baseQuery);

        return new PageList<T>(totals, data);
    }

    /**
     * 批量删除
     * @param ids
     */
    @Override
    @Transactional
    public void batchDelete(Long[] ids) {
        baseMapper.batchDelete(ids);
    }
}
